package com.hbsx.why.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hbsx.why.R;
import com.hbsx.why.base.BaseActivity;
import com.hbsx.why.utils.WaterMarkImage;
import com.hbsx.why.utils.compressphoto.CompressHelper;
import com.hbsx.why.utils.compressphoto.FileUtil;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;

public class DemoPictureCompress extends BaseActivity {

    @BindView(R.id.main_image_old)
    ImageView mainImageOld;
    @BindView(R.id.main_text_old)
    TextView mainTextOld;
    @BindView(R.id.main_image_new)
    ImageView mainImageNew;
    @BindView(R.id.main_text_new)
    TextView mainTextNew;
    private static final int PICK_IMAGE_REQUEST = 1;
    private File oldFile;
    private File newFile;
private Context context=this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    protected void initView() {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.demo_compresspthot;
    }



    public void compress(View view) {
        // 默认的压缩方法，多张图片只需要直接加入循环即可
        //newFile = CompressHelper.getDefault(getApplicationContext()).compressToFile(oldFile);
        String yourFileName = "demo";
//        // 你也可以自定义压缩
        newFile = new CompressHelper.Builder(this)
                .setMaxWidth(720)  // 默认最大宽度为720
                .setMaxHeight(960) // 默认最大高度为960
                .setQuality(80)    // 默认压缩质量为80
                .setCompressFormat(Bitmap.CompressFormat.WEBP) // 设置默认压缩为jpg格式
                .setFileName(yourFileName) // 设置你的文件名
                .setDestinationDirectoryPath(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES).getAbsolutePath())
                .build()
                .compressToFile(oldFile);
        Bitmap oldBitmap=BitmapFactory.decodeFile(newFile.getAbsolutePath());
        Bitmap textBitmap=WaterMarkImage.drawTextToRightBottom(context,oldBitmap,"@"+"我是水印",20,R.color.red,20,20);
        Bitmap imgtextBitmap=WaterMarkImage.createWaterMaskLeftBottom(context,textBitmap,BitmapFactory.decodeResource(getResources(),R.mipmap.ic_ok),20,20);
        mainImageNew.setImageBitmap(imgtextBitmap);
        mainTextNew.setText(String.format("Size : %s", getReadableFileSize(newFile.length())));
        Uri uri = Uri.fromFile(newFile);
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
    }

    public void takePhoto(View view) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*");
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK) {
            if (data == null) {
                showError("Failed to open picture!");
                return;
            }
            try {
                oldFile = FileUtil.getTempFile(this, data.getData());
                mainImageOld.setImageBitmap(BitmapFactory.decodeFile(oldFile.getAbsolutePath()));
                mainTextOld.setText(String.format("Size : %s", getReadableFileSize(oldFile.length())));
                clearImage();
            } catch (IOException e) {
                showError("Failed to read picture data!");
                e.printStackTrace();
            }
        }
    }

    public void showError(String errorMessage) {
        Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show();
    }

    private int getRandomColor() {
        Random rand = new Random();
        return Color.argb(100, rand.nextInt(256), rand.nextInt(256), rand.nextInt(256));
    }
    private void clearImage() {
        mainImageOld.setBackgroundColor(getRandomColor());
        mainImageNew.setImageDrawable(null);
        mainImageNew.setBackgroundColor(getRandomColor());
        mainTextNew.setText("Size : -");
    }
    public String getReadableFileSize(long size) {
        if (size <= 0) {
            return "0";
        }
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
}
